package com.cole.gx095.controller;

import com.cole.gx095.Repository.*;
import com.cole.gx095.domain.*;
import com.cole.gx095.domain.mapper.BillCorDataMapper;
import com.cole.gx095.domain.mapper.CostBillVoMapper;
import com.cole.gx095.domain.mapper.CostVOMapper;
import com.cole.gx095.service.CostService;
import com.cole.gx095.service.StockService;
import com.cole.gx095.controller.utils.CommonRep;
import com.cole.gx095.controller.utils.RedisUtil;
import com.cole.gx095.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/cost")
@CrossOrigin
@Transactional
public class costController {
    @Autowired
    SalecontractRepository salecontractRepository;
    @Autowired
    SalebillRepository salebillRepository;
    @Autowired
    CostService costService;
    @Autowired
    SaleBillgoodsRepository saleBillgoodsRepository;
    @Autowired
    CorrelationRepository correlationRepository;
    @Autowired
    StockService stockService;
    @Autowired
    PurchasecontractRepository purchasecontractRepository;
    @Autowired
    StockgoodsRepository stockgoodsRepository;
    @Autowired
    ArgumentRepository argumentRepository;

    @GetMapping("/List")
    CommonRep List(Integer currentPage, Integer pageSize){
        Page<Salebill> page1 = salebillRepository.findAll(PageRequest.of(currentPage - 1, pageSize));
        List<CostVo> costVoList = new ArrayList<>();
        for (Salebill salebill : page1.getContent()) {
            System.out.println("salebill = " + salebill);
            CostVo conver = CostVOMapper.INSTANCT.conver(salebill);
            conver.setId(salebill.getId());
            conver.setBuyUnit(salecontractRepository.findoneBycontractNum(salebill.getContractNum()).getBuyUnit());
            costVoList.add(conver);
        }
        costVoList.forEach(System.out::println);
        return CommonRep.ok()
                .data("page",page1)
                .data("List",costVoList);
    }

    @PostMapping("/queryBy")
    CommonRep getById( Integer currentPage,
                       Integer pageSize,
                       QueryData queryData){
        Page<Salebill> page1 = costService.findAllBy(queryData, currentPage, pageSize);
        List<CostVo> costVoList = new ArrayList<>();
        for (Salebill salebill : page1.getContent()) {
            CostVo conver = CostVOMapper.INSTANCT.conver(salebill);
            conver.setBuyUnit(salecontractRepository.findoneBycontractNum(salebill.getContractNum()).getBuyUnit());
            costVoList.add(conver);
            if(queryData.getBuyUnit()!=null)
                if(!queryData.getBuyUnit().equalsIgnoreCase(conver.getBuyUnit())){
                    System.out.println("conver = " + conver);
                    costVoList.remove(conver);
                }

        }
        costVoList.forEach(System.out::println);
        return CommonRep.ok()
                .data("page",page1)
                .data("List",costVoList);
    }

    @PostMapping("/queryBillBy")
    CommonRep queryBillBy(@RequestBody BillCorData billCorData) {
        System.out.println("billCorData = " + billCorData);
        List<Stockgoods> allBy = stockService.findAllBy(billCorData);
        List<BillCorData> billCorDataList = new ArrayList<>();
        for (Stockgoods stockgoods : allBy) {
            Purchasecontract byId = purchasecontractRepository.getById(stockgoods.getContractId());
            BillCorData conver = BillCorDataMapper.INSTANCT.conver(stockgoods);
            conver.setStockgoodsId(stockgoods.getId());
            conver.setSupplier(byId.getSupplier());
            conver.setType(byId.getType());
            billCorDataList.add(conver);
        }
        billCorDataList.forEach(System.out::println);
        return CommonRep.ok().data("List",billCorDataList);
    }

    @GetMapping("/getBillById/{id}")
    CommonRep getBillById(@PathVariable Integer id){
        List<CostBillVo> costBillVoList = new ArrayList<>();
        //根据发票id找SaleBillgoods
        List<SaleBillgoods> byBillId = saleBillgoodsRepository.findByBillId(id);
        for (SaleBillgoods saleBillgoods : byBillId) {
            CostBillVo costBillVo = new CostBillVo();
            costBillVo.setSaleBillgoodsId(saleBillgoods.getId());
            costBillVo.setTypeName(saleBillgoods.getTypeName());
            costBillVo.setGoodsName(saleBillgoods.getGoodsName());
            costBillVo.setModle(saleBillgoods.getModle());
            costBillVo.setGoodsUnitPrice(saleBillgoods.getGoodsUnitPrice());
            costBillVo.setGoodsAccount(saleBillgoods.getGoodsAccount());
            costBillVoList.add(costBillVo);
        }
        List<Correlation> byBillId1 = correlationRepository.findByBillId(id);
        for (Correlation correlation : byBillId1) {
            CostBillVo conver = CostBillVoMapper.INSTANCT.conver(correlation);
            conver.setGoodsAccount(correlation.getCorrelationAccount());
            costBillVoList.add(conver);
        }
        costBillVoList.forEach(System.out::println);
        return CommonRep.ok().data("BillTableData",costBillVoList);
    }

    /**
     * 操作库存表和关联表
     * 判断发票是否关联完成
     * @param billCorDataList
     * @return
     */
    @PostMapping("/addCor")
    CommonRep addCor(@RequestBody List<BillCorData> billCorDataList){
        Salebill salebill = salebillRepository.findoneBybillNum(billCorDataList.get(0).getSaleBillNum());

        for (BillCorData billCorData : billCorDataList) {
            Stockgoods byId = stockgoodsRepository.getById(billCorData.getStockgoodsId());
            byId.setCorrelationAccount(billCorData.getCorrelationAccount()+byId.getCorrelationAccount());
            byId.setRemainAccount(byId.getRemainAccount() - billCorData.getCorrelationAccount());
            stockgoodsRepository.save(byId);

            Correlation correlation = new Correlation();
            correlation.setSaleBillId(salebill.getId());
            correlation.setSaleBillNum(salebill.getBillNum());
            correlation.setSaleContractId(salebill.getContractId());
            correlation.setSaleContractNum(salebill.getContractNum());

            correlation.setPurchanseBillId(byId.getBillId());
            correlation.setPurchanseBillNum(byId.getBillNum());
            correlation.setPurchanseContractId(byId.getContractId());
            correlation.setPurchanseContractNum(byId.getContractNum());

            correlation.setStockGoodsId(billCorData.getStockgoodsId());
            correlation.setTypeName(billCorData.getTypeName());
            correlation.setModle(billCorData.getModle());
            correlation.setGoodsName(billCorData.getGoodsName());
            correlation.setGoodsUnitPrice(billCorData.getGoodsUnitPrice());

            correlation.setCorrelationAccount(billCorData.getCorrelationAccount());
            correlation.setCorrelationAmount(billCorData.getCorrelationAccount()*billCorData.getGoodsUnitPrice());
            correlation.setCreateAdminTrueName(RedisUtil.mget("LoginName"));
            correlation.setCorrelationType(0);//0成本占用 1补票占用
            correlation.setStatus(0);//0正常 1作废
            correlationRepository.save(correlation);
        }
        //计算关联率 并将关联金额和关联率存到salebill表
        Double billcorrelationAmount = 0.0;
        List<Correlation> correlationList = correlationRepository.findByBillId(salebill.getId());
        for (Correlation correlation : correlationList) {
            if(correlation.getStatus()==0)//判断关联是否生效
                billcorrelationAmount += correlation.getCorrelationAmount();
        }
        salebill.setCorrelationAmount(billcorrelationAmount);
        salebill.setCorrelationRate(billcorrelationAmount / salebill.getBillAccount() * 100);
        if(salebill.getCorrelationRate() > argumentRepository.getById(1).getValue()){
            salebill.setStatus(1);
        }
        salebillRepository.save(salebill);

        //更新发票所关联的销售合同关联率
        Double contractCorAmount = salebillRepository.sumAmountBycontractNum(salebill.getContractNum());
        Salecontract salecontract = salecontractRepository.findoneBycontractNum(salebill.getContractNum());
        salecontract.setCorrelationAmount(contractCorAmount);
        salecontract.setCorrelationRate(contractCorAmount / salecontract.getContractAmount() * 100);
        if(salecontract.getCorrelationRate() > argumentRepository.getById(1).getValue()){
            salecontract.setStatus(1);
        }
        salecontractRepository.save(salecontract);
        return CommonRep.ok();
    }

    /**
     * 修改关联操作的状态
     * 发票关联重新计算
     * 库存也重新回退
     * 判断发票是否关联未完成
     * 涉及表cor和salebill stock
     * @param id
     * @return
     */
    @PostMapping("/corDel/{id}")
    CommonRep corDel(@PathVariable Integer id){
        System.out.println("corDel/id = " + id);
        //修改关联表
        Correlation byId = correlationRepository.getById(id);
        byId.setStatus(1);
        correlationRepository.save(byId);

        //库存回退该关联操作之前
        Stockgoods stockgoods = stockgoodsRepository.getById(byId.getStockGoodsId());
        stockgoods.setCorrelationAccount(stockgoods.getCorrelationAccount() - byId.getCorrelationAccount());
        stockgoods.setRemainAccount(stockgoods.getRemainAccount() + byId.getCorrelationAccount());
        stockgoodsRepository.save(stockgoods);

        //计算关联率 并将关联金额和关联率存到salebill表
        Double billcorrelationAmount = 0.0;
        Integer saleBillId = byId.getSaleBillId();
        Salebill salebill = salebillRepository.getById(saleBillId);
        List<Correlation> correlationList = correlationRepository.findByBillId(saleBillId);
        for (Correlation correlation : correlationList) {
            if(correlation.getStatus()==0)//判断关联是否生效
                billcorrelationAmount += correlation.getCorrelationAmount();
        }
        salebill.setCorrelationAmount(billcorrelationAmount);
        salebill.setCorrelationRate(billcorrelationAmount / salebill.getBillAccount() * 100);
        if(salebill.getCorrelationRate() <= argumentRepository.getById(1).getValue()){
            salebill.setStatus(0);
        }
        salebillRepository.save(salebill);

        return CommonRep.ok();
    }

    /**
     * 强制完成进入补票界面
     * @param billNum
     * @return
     */
    @PostMapping("/billFinish/{billNum}")
    CommonRep billFinish(@PathVariable String billNum){
        Salebill salebill = salebillRepository.findoneBybillNum(billNum);
        System.out.println("salebill = " + salebill);
        salebill.setBillstatus(1);
        salebillRepository.save(salebill);
        return CommonRep.ok();
    }

    /**
     * 撤销强制完成
     * @param billNum
     * @return
     */
    @PostMapping("/billFinishback/{billNum}")
    CommonRep billFinishback(@PathVariable String billNum){
        Salebill salebill = salebillRepository.findoneBybillNum(billNum);
        System.out.println("salebill = " + salebill);
        if(salebill.getBillstatus()==1)
            salebill.setBillstatus(0);
        salebillRepository.save(salebill);
        return CommonRep.ok();
    }

}
